package com.opengate.base.exception;

import com.opengate.base.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description 全局异常处理
 * @date 2023/4/26 5:46 PM
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /** 定义参数校验异常处理 提示后缀 */
    private static final String BAD_REQUEST_MSG = " Check failed";

    /**
     * 处理业务异常
     *
     * @param e 业务异常
     * @return Result
     */
    @ExceptionHandler(OpenGateException.class)
    public Result<Object> baseExceptionHandler(OpenGateException e) {
        return Result.fail(e.getCode(), e.getMessage());
    }

    /**
     * 处理请求参数异常
     *
     * @param e 请求参数异常
     * @return Result
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<Object> missingServletRequestParameterExceptionHandler(
            MissingServletRequestParameterException e) {
        return Result.fail(e.getParameterName() + BAD_REQUEST_MSG);
    }

    /**
     * 处理 json 请求体调用接口校验失败抛出的异常
     *
     * @param e json请求体调用接口校验失败抛出的异常
     * @return Result
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> methodArgumentNotValidExceptionHandler(
            MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect =
                fieldErrors.stream()
                        .map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(Collectors.toList());
        return Result.fail(ExceptionCodeEnum.sys_0003.getCode(), collect.toString());
    }

    /**
     * 处理 form data方式调用接口校验失败抛出的异常
     *
     * @param e form data方式调用接口校验失败抛出的异常
     * @return Result
     */
    @ExceptionHandler(BindException.class)
    public Result<Object> bindExceptionHandler(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect =
                fieldErrors.stream()
                        .map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(Collectors.toList());
        return Result.fail(ExceptionCodeEnum.sys_0003.getCode(), collect.toString());
    }

    /**
     * 处理单个参数校验失败抛出的异常
     *
     * @param e 单个参数校验失败抛出的异常
     * @return Result
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Object> constraintViolationExceptionHandler(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        List<String> collect =
                constraintViolations.stream()
                        .map(ConstraintViolation::getMessage)
                        .collect(Collectors.toList());
        return Result.fail(ExceptionCodeEnum.sys_0003.getCode(), collect.toString());
    }

    /**
     * 处理以上处理不了的其他异常
     *
     * @param e 其他异常
     * @return Result
     */
    @ExceptionHandler(Exception.class)
    public Result<Object> exceptionHandler(Exception e) {
        log.error("unHandle exception: ", e);
        if (e instanceof OpenGateException) {
            // 业务异常
            OpenGateException ase = (OpenGateException) e;
            return Result.fail(ase.getCode(), ase.getMsg());
        } else {
            // 其他异常
            return Result.fail(
                    ExceptionCodeEnum.sys_0001.getCode(), ExceptionCodeEnum.sys_0001.getDesc());
        }
    }
}
